package com.orcsystem.auth.service.impl;

import com.orcsystem.auth.Feign.ThirdPartFeignService;
import com.orcsystem.auth.entity.vo.UserRegistVo;
import com.orcsystem.auth.service.AuthService;
import com.orcsystem.common.constant.RedisConstant;
import com.orcsystem.common.exception.BizCodeEnume;
import com.orcsystem.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @CreateData: 2020/12/21-15:39
 * Author   AiHongSen
 * 方法说明
 * SL 查询、DL 删除、UP 更新、IN 新增方法
 * AuthServiceImpl->作用:
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public R sendCode(String mobile) {
        String k = RedisConstant.SMS_CACHE_PREFIX + mobile;
        String redisCode = redisTemplate.opsForValue().get(k);
            if (StringUtils.isEmpty(redisCode)){
            // 请求验证码
            send(k,mobile);
        }else {
            long l = Long.parseLong(redisCode.split("_")[1]);
            // 当前时间 减去 存入redis时间 小于60秒
            long l1 = System.currentTimeMillis();
            if ((l1 - l) < 60000*60*24*30){
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        return R.ok();
    }

    @Override
    public R regist(UserRegistVo vo, RedirectAttributes attributes) {
        String redisValue = redisTemplate.opsForValue().get(RedisConstant.SMS_CACHE_PREFIX + vo.getMobile()).split("_")[0];
        if (StringUtils.isNotEmpty(redisValue)){
            if (vo.getCode().equals(redisValue)){
                // 成功
            }
        }else {
            // 空
            HashMap<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            // 重定向到注册页

        }

        return null;
    }

    /**
     * 发送验证码
     */
    private void send(String k,String mobile){
        String code = UUID.randomUUID().toString().substring(0,5);
        String redisCode = code+"_"+System.currentTimeMillis();
        // 保存到redis 在进行返回
        redisTemplate.opsForValue().set(k,redisCode,60*24*30, TimeUnit.MINUTES);
        thirdPartFeignService.reqSms(mobile,code);
    }
}
